// pages/launch/launch.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: "1", // 当前选择的上屏类型
    isAgree: false, // 同意协议
    protocolMaskShow: false,  // 显示协议
    launchImg: "", // 上屏图片
    cinemaMaskShow: false,
    launchType: "立即投放", // 投放类型
    duringList: [], // 时长列表
    chooseIndex: 0,
    playTime: "", // 上屏日期
    cinemaId: "",
    cinemaName: "",
    spareTime: "", // 影院剩余时长
    isContact: false, // 是否同意被联系
    cityArr: [],
    cityName: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOnceDuringList();
    var date = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
    this.setData({
      playTime: app.getCurrentDate(1, date)
    });

    if (app.globalData.chooseCity === "" || app.globalData.chooseCity === app.globalData.locationCity) {
      this.setData({
        cityName: app.globalData.locationCity
      })
    } else {
      this.setData({
        cityName: app.globalData.chooseCity,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.resultImgUrl !== ""){
      this.setData({
        launchImg: app.globalData.resultImgUrl
      })
    }
    this.getCinema();
    if (app.globalData.chooseCinema !== ""){
      this.setData({
        cinemaName: app.globalData.chooseCinema,
        cinemaId: app.globalData.cinemaId
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 上传图片
  uploadPoster(){
    wx.navigateTo({
      url: '../editImg/editImg',
    })
  },

  // 选择上屏类型
  changeTab(e){
    var index = e.currentTarget.dataset.index;
    if (index !== this.data.currentTab){
      if (e.currentTarget.dataset.index === "1"){
        this.getOnceDuringList()
      }else{
        this.getAppDuringList();
      }
    }
    if (index == 1) {
      this.setData({
        launchType: "立即投放"
      })
    } else {
      this.setData({
        launchType: "预约投放"
      })
    }
    this.setData({
      currentTab: index
    })
  },

  // 切换城市
  changeCity(e){
    this.setData({
      cityName: e.detail.value[1].split("市")[0]
    });
    this.getCinema();
  },


  // 选择上屏时长
  chooseDuring(e){
    var index = e.currentTarget.dataset.index;
    this.setData({
      chooseIndex: index
    });
    app.globalData.chooseDuring = this.data.duringList[index];
  },

  // 是否同意被勾搭
  isContact(e){
    this.setData({
      isContact: e.detail.value
    })
  },

  // 同意协议
  isAgree(e){
    this.setData({
      isAgree: !this.data.isAgree
    })
  },

  // 查看协议
  agreement(){
    this.setData({
      protocolMaskShow: true
    })
  },

  // 协议隐藏
  proTocolSure: function () {
    this.setData({
      protocolMaskShow: false
    })
  },

  // 选择上屏日期
  bindDateChange(e){
    if (e.detail.value < this.data.playTime){
      app.showError("至少选择今天以后的日期")
    }else{
      this.setData({
        playTime: e.detail.value
      })
    }
  },

  // 点击影院
  cinematap: function () {
    this.getCinema();
    this.setData({
      cinemaMaskShow: true
    })
  },

  // 选择区域
  areaChoose: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      cinemaArr: this.data.areaList[index].children,
      currentIndex: index
    })
  },

  // 选择影院
  chooseCinema: function (e) {
    this.setData({
      cinemaIndex: e.currentTarget.dataset.index,
    });
  },

  // 确定选择影院
  sureCinema: function () {
    this.setData({
      cinemaName: this.data.cinemaArr[this.data.cinemaIndex].cinema_name,
      cinemaId: this.data.cinemaArr[this.data.cinemaIndex].region_id,
      cinemaMaskShow: false
    });
    this.adInquiry(this.data.cinemaId);
    app.globalData.chooseCinema = this.data.cinemaName;
    app.globalData.cinemaId = this.data.cinemaId;
  },

  // 取消
  hideMask: function () {
    this.setData({
      cinemaMaskShow: false
    });
  },

  // 获取影院
  getCinema: function () {
    wx.showLoading({
      title: '加载中',
    });
    var data = {};
    if (this.data.cityName === app.globalData.locationCity) {
      data = {
        'access_token': app.globalData.accessToken,
        'city_name': app.globalData.locationCity,
        'current_lon': app.globalData.longitude,
        'current_lat': app.globalData.latitude,
      }
    } else {
      data = {
        'access_token': app.globalData.accessToken,
        'city_name': this.data.cityName,
      }
    }
    wx.request({
      url: app.globalData.url + '/ad/cinema/list',
      method: "POST",
      data: data,
      success: res => {
        var areaList = res.data.data.cinema_list.all_cinema_info;
        var locationCinema = res.data.data.cinema_list.current_cinema_info;
        this.setData({
          areaList: areaList,
          cinemaName: locationCinema.cinema_name,
          cinemaId: locationCinema.region_id,
          cinemaArr: areaList[0].children
        });
        wx.hideLoading();
        this.adInquiry(locationCinema.region_id);
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 广告询量
  adInquiry: function (cinemaId) {
    var playTime = "", playFrequency = "", during = "";
    if (this.data.currentTab == 1){
      var date = new Date();
      playTime = app.getCurrentDate(2, date);
      playFrequency = 1;
      during = this.data.duringList[this.data.chooseIndex].during.split("s")[0];
    }else{
      playTime = this.data.playTime;
      playFrequency = this.data.duringList[this.data.chooseIndex].during.split("/")[0].split("次")[0];
      during = this.data.duringList[this.data.chooseIndex].during.split("/")[1].split("秒")[0]
    }
    wx.request({
      url: app.globalData.url + '/ad/inquiry/info',
      method: "POST",
      data: {
        'access_token': app.globalData.accessToken,
        'cinema_id': cinemaId,
        'during': during,
        'ad_time': playTime,  // 预约投放上屏时间
        'play_frequency': playFrequency  // 预约投放播放频次
      },
      success: res => {
        if (res.data.err_code === 200) {
          this.setData({
            spareTime: res.data.data.inquiry_data.spare_time
          });
          if (res.data.data.inquiry_data.spare_time <= 0) {
            app.showError("当前影院屏幕所剩时长不足，请修改影院");
          }
        }
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 获取个人上屏时长列表
  getOnceDuringList: function () {
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + '/data/nowScreen',
      success: res => {
        if (res.data) {
          this.setData({
            duringList: res.data,
          });
        }
        wx.hideLoading();
      },
      fail: res => {
        console.log(res);
        app.showError("服务器错误")
      }
    })
  },

  // 获取商业上屏时长列表
  getAppDuringList: function () {
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + '/data/appScreen',
      success: res => {
        var timeAppList = [];
        if (res.data) {
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].type === "全天轮播") {
              res.data[i].playNum = res.data[i].during.split("/")[0];
              res.data[i].time = res.data[i].during.split("/")[1].split("秒")[0]
              timeAppList.push(res.data[i]);
            } 
          }
          this.setData({
            duringList: timeAppList,
          })
        }
        wx.hideLoading();
      },
      fail: res => {
        console.log(res);
        app.showError("服务器错误")
      }
    })
  },

  // 模板消息
  sendFormId: function (formId) {
    wx.request({
      url: app.globalData.baseUrl + '/data/getFormId',
      header: {
        "unicorn": app.globalData.token
      },
      data: {
        formId: formId
      },
      success: res => {
        console.log(res);
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  // 提交订单
  submitOrder(e) {
    this.sendFormId(e.detail.formId);
    if (this.data.spareTime <= 0) {
      app.showError("当前影院所剩时长不足，请修改影院");
    } else if (this.data.isAgree == false) {
      app.showError("请阅读并同意投放协议");
    } else if (this.data.launchImg == "") {
      app.showError("请先上传图片");
    } else {
      this.payment();
    }
  },

  // 提交
  payment: function () {
    wx.showLoading({
      title: '正在提交',
    })
    var playTime = "", playFrequency = "", during = "";
    var price = this.data.duringList[this.data.chooseIndex].now_price;
    if (this.data.currentTab == 1){
      var date = new Date();
      playTime = app.getCurrentDate(2, date);
      app.globalData.playFrequency = 1;
      playFrequency = 1;
      during = this.data.duringList[this.data.chooseIndex].during.split("s")[0];
      app.globalData.launchType = 1;
    }else{
      playTime = this.data.playTime;
      app.globalData.playFrequency = this.data.duringList[this.data.chooseIndex].during.split("/")[0].split("次")[0];
      playFrequency = this.data.duringList[this.data.chooseIndex].during.split("/")[0].split("次")[0];
      during = this.data.duringList[this.data.chooseIndex].during.split("/")[1].split("秒")[0]
      app.globalData.launchType = 2
    }
    wx.request({
      url: app.globalData.baseUrl + '/data/saveOrder',
      method: "GET",
      header: {
        "unicorn": app.globalData.token
      },
      data: {
        "thQspOrderList.img": this.data.launchImg,
        "thQspOrderList.cinema_name": this.data.cinemaName,
        "thQspOrderList.type": this.data.launchType,
        "thQspOrderList.during": during,
        "thQspOrderList.price": app.changeToBase64(price),
        "thQspOrderList.true_price": Number(price) * 100,
        "thQspOrderList.play_time": playTime,
        "greet": this.data.isContact === true ? 0 : 1,
      },
      success: res => {
        if (res.data.errCode == "00000") {
          app.globalData.orderData = {
            "order_no": res.data.orderNo,
            "price": price,
            "during": during,
            "playTime": playTime,
            "cinema_id": this.data.cinemaId,
            "cinema_name": this.data.cinemaName,
            'img': this.data.launchImg, 
          }
          app.globalData.orderId = res.data.orderNo;
          app.globalData.payData = res.data.WxPay;
          
          wx.navigateTo({
            url: '../orderPay/orderPay',
          });
          wx.hideLoading();
        }
      },
      fail: res => {
        console.log(res);
      }
    })
  },

  

})